/**
 * 
 */
package info.niwota.fwrite;

import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * @author qiangli
 * 
 */
public class ResourceImageElement extends Element {

	private static final long serialVersionUID = 1L;

	private static final String KEY_RESID = "resid";
	
	public int resource;
	
	private transient Bitmap bitmap;

	/**
	 * 
	 */
	public ResourceImageElement(int resource) {
		this.resource = resource;
		this.width = 32;
		this.height = 32;
	}

	private Bitmap getBitmap() {
		if (bitmap == null) {
			bitmap = loadImage(ctx);
		}
		return bitmap;
	}

	private Bitmap loadImage(Context ctx) {
		return BitmapFactory.decodeResource(ctx.getResources(), resource);
	}

	@Override
	public void draw(Canvas canvas, Paint paint, float x, float y,
			float height, float lh) {
		Bitmap bm = getBitmap();
		if (bm != null) {
			canvas.drawBitmap(bm, x, y, paint);
		}
	}

	public ResourceImageElement(JSONObject obj) throws Exception {
		super(obj);
		
		this.resource = obj.getInt(KEY_RESID);
	}

	public JSONObject toJSON() throws Exception {
		JSONObject obj = super.toJSON(ELEMENT_RESOURCE_IMAGE);
		
		obj.put(KEY_RESID, resource);
		return obj;
	}
}
